﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Reflection;

namespace AFI.Speargun.Web.Core
{
    public static class SelectListBuilder
    {
        public static SelectList Create(Type enumType, object selected)
        {
            if (!enumType.IsEnum)
                throw new ArgumentException();

            Dictionary<int, string> dict = new Dictionary<int, string>();

            string[] enumNames = Enum.GetNames(enumType);
            foreach (var i in enumNames)
            {
                int key = (int)Enum.Parse(enumType, i);

                FieldInfo fi = enumType.GetField(i);
                string value;
                object[] attrs = fi.GetCustomAttributes(typeof(EnumTextValueAttribute), false);
                if (attrs.Length == 1)
                    value = ((EnumTextValueAttribute)attrs[0]).Text;
                else
                    value = i;

                dict.Add(key, value);
            }

            return new SelectList(dict, "Key", "Value", selected);
        }

        public static SelectList Create<T>(IEnumerable<T> collection, string keyPropertyName, string valuePropertyName, object selected)
        {
            Dictionary<Guid, string> dict = new Dictionary<Guid, string>();

            PropertyInfo keyProperty = typeof(T).GetProperty(keyPropertyName);
            PropertyInfo valueProperty = typeof(T).GetProperty(valuePropertyName);

            foreach (var i in collection)
            {
                Guid key = new Guid(keyProperty.GetValue(i, null).ToString());
                string value = valueProperty.GetValue(i, null).ToString();

                dict.Add(key, value);
            }

            return new SelectList(dict, "Key", "Value", selected);

        }
    }
}
